package com.books.dao;

import com.books.model.entity.question.Question;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class QuestionDao {
 
 
    @Autowired
    private MongoTemplate mongoTemplate;
 
    /**
     * 创建对象
     */
    public void saveTest(Question question) {
        mongoTemplate.save(question);
    }

    /**
     * 根据问题id查询对象
     * @return
     */
    public Question findTestById(String _id) {
        Query query = new Query(Criteria.where("_id").is(_id));
        Question question = mongoTemplate.findOne(query, Question.class);
        return question;
    }
 
    /**
     * 根据书籍id和书籍类别id查询
     * @return
     */
    public List<Question> findTestByName(Integer bookId,Integer bookTypeId) {
        Criteria c1=Criteria.where("bookId").is(bookId);
        Criteria c2=Criteria.where("bookTypeId").is(bookTypeId);
        List<Criteria> list=new ArrayList<Criteria>();
        list.add(c1);
        list.add(c2);
        Criteria[] arr=new Criteria[list.size()];
        list.toArray(arr);
        Criteria criteria=new Criteria().andOperator(arr);
        Query query=new Query(criteria);
        List<Question> questions =  mongoTemplate.find(query , Question.class);
        return questions;
    }
 
    /**
     * 更新对象
     */
    public void updateTest(Question question) {
        Query query=new Query(Criteria.where("_id").is(question.get_id()));
        Update update= new Update().set("text", question.getText());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,Question.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,TestEntity.class);
    }
 
    /**
     * 删除对象
     * @param id
     */
    public void deleteTestById(Integer id) {
        Query query=new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,Question.class);
    }
}